package com.zking.seckillpro.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zking.seckillpro.exception.BusinessException;
import com.zking.seckillpro.model.User;
import com.zking.seckillpro.mapper.UserMapper;
import com.zking.seckillpro.service.IRedisService;
import com.zking.seckillpro.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zking.seckillpro.util.*;
import com.zking.seckillpro.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>
 * �û���Ϣ�� 服务实现类
 * </p>
 *
 * @author zking
 * @since 2022-03-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IRedisService redisService;
    @Override
    public JsonResponseBody<?> userLogin(UserVo userVo, HttpServletRequest req, HttpServletResponse resp) {
        //1.判断输入的账号和密码是否为空
//        if(StringUtils.isEmpty(userVo.getMobile())||StringUtils.isEmpty(userVo.getPassword())){
//           throw new BusinessException(JsonResponseStatus.USERNAME_PASSWORD_EMPTY);
//            // return new JsonResponseBody<>(JsonResponseStatus.USERNAME_PASSWORD_EMPTY);
//        }
        //2.判断输入的账号（手机号码）格式是否正确
        if(!ValidatorUtils.isMobile(userVo.getMobile())){
            throw new BusinessException(JsonResponseStatus.MOBILE_ERROR);
//            return new JsonResponseBody<>(JsonResponseStatus.MOBILE_ERROR);
        }

        //3.根据账号获取对应用户的对象信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", userVo.getMobile()));
        //4判断用户对象是否存在
        if(null==user){
            throw new BusinessException(JsonResponseStatus.USER_EMPTY);
           // return new JsonResponseBody<>(JsonResponseStatus.USER_EMPTY);
        }
        //5.判断用户对象的密码与输入的密码是否一致
        //将前端传入的一道加密密码与user对象中的随机盐进行二次加密得到二道密码，再与数据库中的二道密码进行对比
        String pwd2= MD5Utils.formPassToDbPass(userVo.getPassword(),user.getSalt());
        if(!user.getPassword().equals(pwd2)){
            throw new BusinessException(JsonResponseStatus.PASSWORD_ERROR);
//            return new JsonResponseBody<>(JsonResponseStatus.PASSWORD_ERROR);
        }

        //采用uuid方式作为Token令牌
        String token= UUID.randomUUID().toString().replace("-","");
        //将生成的token令牌保存到cookies中
        CookieUtils.setCookie(req,resp,"token",token,7200);
        //将生成的token与user对象进行绑定并保存到session中
        //req.getSession().setAttribute(token,user);
        //优化：将用户对象与生成的token保存到redis中
        redisService.setUserToRedis(token,user);

        return new JsonResponseBody<>();
    }
}
